<?php

namespace Database\Seeders;

use App\Models\Post;
use App\Models\Reply;
use App\Models\ReplyLike;
use App\Models\User;
use App\Services\ReplyService;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class ReplySeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $posts = Post::all();
        $users = User::all();

        if ($posts->isEmpty() || $users->isEmpty()) {
            $this->command->warn('没有帖子或用户数据，请先运行 PostSeeder 和 UserSeeder');
            return;
        }

        $this->command->info('开始创建回复数据...');

        DB::transaction(function () use ($posts, $users) {
            foreach ($posts as $post) {
                // 每个帖子创建 0-5 个主回复（有些帖子可能没有回复）
                $mainReplyCount = fake()->numberBetween(0, 5);
                
                if ($mainReplyCount === 0) {
                    continue; // 跳过没有回复的帖子
                }

                $mainReplies = [];
                $postCreatedAt = $post->created_at;

                for ($i = 0; $i < $mainReplyCount; $i++) {
                    // 随机选择一个用户作为回复者（不能是帖子作者）
                    $authorId = $post->user_id;
                    $replierId = $users->where('id', '!=', $authorId)->random()->id;
                    $replier = $users->firstWhere('id', $replierId);

                    if (!$replier) {
                        continue;
                    }

                    // 创建主回复
                    $reply = Reply::create([
                        'user_id' => $replierId,
                        'post_id' => $post->id,
                        'parent_id' => null,
                        'content' => $this->generateReplyContent(),
                        'like_count' => 0,
                        'created_at' => fake()->dateTimeBetween($postCreatedAt, 'now'),
                        'updated_at' => now(),
                    ]);

                    $mainReplies[] = $reply;
                    $postCreatedAt = $reply->created_at; // 下一个回复的时间基于上一个回复
                }

                // 为每个主回复创建 0-3 个楼中楼回复
                foreach ($mainReplies as $mainReply) {
                    $nestedReplyCount = fake()->numberBetween(0, 3);
                    
                    if ($nestedReplyCount === 0) {
                        continue;
                    }

                    $mainReplyCreatedAt = $mainReply->created_at;

                    for ($j = 0; $j < $nestedReplyCount; $j++) {
                        // 随机选择一个用户作为楼中楼回复者
                        $nestedReplierId = $users->random()->id;
                        $nestedReplier = $users->firstWhere('id', $nestedReplierId);

                        if (!$nestedReplier) {
                            continue;
                        }

                        // 创建楼中楼回复
                        Reply::create([
                            'user_id' => $nestedReplierId,
                            'post_id' => $post->id,
                            'parent_id' => $mainReply->id,
                            'content' => $this->generateNestedReplyContent($mainReply->user),
                            'like_count' => 0,
                            'created_at' => fake()->dateTimeBetween($mainReplyCreatedAt, 'now'),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }

            // 创建回复点赞数据
            $this->createReplyLikes($users);

            // 更新统计信息
            $this->updateStatistics();
        });

        // 更新所有帖子的回复数（只统计主回复）
        foreach ($posts as $post) {
            $post->update([
                'reply_count' => Reply::where('post_id', $post->id)
                    ->whereNull('parent_id')
                    ->count(),
            ]);
        }

        $totalReplies = Reply::count();
        $mainReplies = Reply::whereNull('parent_id')->count();
        $nestedReplies = Reply::whereNotNull('parent_id')->count();
        $totalReplyLikes = ReplyLike::count();

        $this->command->info("回复数据填充完成！");
        $this->command->info("共创建 {$totalReplies} 条回复（主回复：{$mainReplies}，楼中楼：{$nestedReplies}）");
        $this->command->info("共创建 {$totalReplyLikes} 条回复点赞记录");
    }

    /**
     * 生成主回复内容
     */
    private function generateReplyContent(): string
    {
        $faker = fake('zh_CN');

        $prefixes = [
            '说得很有道理',
            '我也遇到过类似的问题',
            '感谢分享',
            '学到了',
            '不错的方法',
            '我试试这个方法',
            '赞同楼主的观点',
            '补充一点',
            '个人觉得',
            '这个问题我也想知道',
            '根据我的经验',
            '我也有同样的疑问',
            '顶一下',
            '支持一下',
            '很有帮助',
            '感谢解答',
            '受教了',
            '有道理',
            '赞同',
            '我也这么觉得',
            '说得对',
            '学习了',
            '感谢楼主',
            '不错的分享',
            '收藏了',
            '值得一试',
            '有帮助',
            '明白了',
            '谢谢分享',
            '好文',
        ];

        $bodies = [
            '，我之前也是这样做的。',
            '，这个方法确实有效。',
            '，期待楼主更多分享。',
            '，希望能帮助到更多人。',
            '，大家可以参考一下。',
            '，有问题可以继续交流。',
            '，我补充一些细节。',
            '，希望对你有所帮助。',
            '，有什么问题随时问我。',
            '，继续加油！',
        ];

        $content = $faker->randomElement($prefixes) . $faker->sentence(5, 15) . $faker->randomElement($bodies);
        
        // 30% 概率生成更长的回复
        if (fake()->boolean(30)) {
            $content .= "\n\n" . $faker->paragraph(1, 2);
        }

        return $content;
    }

    /**
     * 生成楼中楼回复内容（可以 @ 被回复的用户）
     */
    private function generateNestedReplyContent($parentUser): string
    {
        $faker = fake('zh_CN');

        $prefixes = [
            '赞同',
            '我也是这么想的',
            '说得对',
            '感谢解答',
            '学到了',
            '补充一下',
            '我也有同样的疑问',
            '有道理',
            '支持',
            '顶',
            '明白了',
            '谢谢',
        ];

        // 有些楼中楼回复会 @ 被回复的用户
        $content = '';
        if (fake()->boolean(40) && $parentUser) {
            $content = '@' . ($parentUser->nickname || $parentUser->name) . ' ';
        }

        $content .= $faker->randomElement($prefixes) . '，' . $faker->sentence(3, 10);

        return $content;
    }

    /**
     * 创建回复点赞数据
     */
    private function createReplyLikes($users): void
    {
        $replies = Reply::all();

        foreach ($replies as $reply) {
            // 10-40% 的用户会点赞回复（根据回复的热度）
            $likeProbability = fake()->numberBetween(10, 40);
            $likeCount = (int)($users->count() * $likeProbability / 100);
            $likeCount = min($likeCount, $users->count());

            if ($likeCount > 0) {
                $likers = $users->random($likeCount);
                foreach ($likers as $user) {
                    // 确保作者不会给自己点赞（概率较低，但不完全禁止）
                    if ($user->id !== $reply->user_id || fake()->boolean(5)) {
                        ReplyLike::create([
                            'reply_id' => $reply->id,
                            'user_id' => $user->id,
                            'created_at' => fake()->dateTimeBetween($reply->created_at, 'now'),
                            'updated_at' => now(),
                        ]);
                    }
                }
            }
        }
    }

    /**
     * 更新统计信息
     */
    private function updateStatistics(): void
    {
        $replies = Reply::all();

        foreach ($replies as $reply) {
            $likeCount = ReplyLike::where('reply_id', $reply->id)->count();
            $reply->update(['like_count' => $likeCount]);
        }
    }
}
